<template>
  <div class="vcard-page">
        <input id="topicId" type="hidden" value="1"/>
        <input id="isAdmin" type="hidden" value=""/>

        <!-- 导航菜单 -->
        <nav class="cli_nav new-light scene_mobile clearfix">
      <ul class="sub_nav sub_mobile_nav cli_head_container clearfix">
        <li><router-link class="t06971093650622ab_sep [navigation_text]" to="/qrcode/text" @click="StatisticsData(120,11)" title="生成文本二维码">文本</router-link></li>
        <li><router-link class="tab_sep [navigation_url]" to="/qrcode/url" @click="StatisticsData(120,12)" title="生成网址二维码">网址</router-link></li>
        <li><router-link class="tab_sep [navigation_files]" to="/qrcode/files" @click="StatisticsData(120,13)" title="生成文件二维码">文件</router-link></li>
        <li><router-link class="tab_sep [navigation_img]" to="/qrcode/img" @click="StatisticsData(120,14)" title="生成图片二维码">图片</router-link></li>
        <li><router-link class="tab_sep [navigation_multimedia]" to="/qrcode/multimedia" @click="StatisticsData(120,15)" title="生成音视频二维码">音视频</router-link></li>
        <li><router-link class="tab_sep on [navigation_vcard]" to="/qrcode/vcard" @click="StatisticsData(120,16)" title="名片二维码">名片</router-link></li>
        <li><router-link class="tab_sep [navigation_weixin]" to="/qrcode/weixin" @click="StatisticsData(120,17)" title="美化微信二维码">微信</router-link></li>
        <li><router-link class="tab_sep [navigation_form]" to="/qrcode/form" @click="StatisticsData(120,124001)" title="记录表单">表单</router-link></li>
        <li><router-link class="tab_sep [navigation_batch]" to="/qrcode/batch" title="批量生码">批量生码</router-link></li>
        <li><router-link class="tab_sep [navigation_tools]" to="/qrcode/tools" @click="StatisticsData(120,161)" title="更多高级功能">更多工具</router-link></li>
        <li class="pull-right right-nav-items none-after-form">
          <ul>
            <li class="pull-left nav-tool-popover-scan-new">
              <router-link class="template-code" data-analyze="8,118010" to="/qrcode/template" id="__index_template">
                <i class="clifont anticon-moban1"></i>
                模板库建码
              </router-link>
            </li>
          </ul>
        </li>
      </ul>
    </nav>

        <!-- Main banner with vcard form -->
        <div class="banner new-light mobile-scene-min-width adaptive-min-height">
            <div class="page-main-content">
                <div class="row" style="margin: 0px;">
                    <div class="tab-content clearfix">
                        <div aria-expanded="false" class="tab-pane animated fadeIn active clearfix" id="tab1" style="min-width: 1000px;">
                            <div class="personCreateVcard">
                                <input name="pVcardContent" type="hidden" value=""/>

                                <!-- Vcard Form -->
                                <div class="person-vcard clearfix" id="person-form">
                                    <!-- Avatar Section -->
                                    <div class="avator">
                                        <img alt="" id="upload-img" :src="avatarUrl" @error="handleImageError" @load="handleImageLoad"/>
                                        <div class="upload pointer" id="upload-btn" @click="triggerAvatarUpload">
                                            <input accept=".jpg, .jpeg, .png, .bmp" class="uploadfile" hidden="" id="uploadfile" type="file" @change="handleAvatarUpload"/>
                                            <div class="uploadClick">上传</div>
                                        </div>
                                    </div>

                                    <!-- Left Info Section -->
                                    <div class="left-info">
                                        <div class="p-vcard-info">
                                            <label class="required" for="name">姓名</label>
                                            <input autocomplete="off" data-id="13" disableautocomplete="" name="name" type="text" v-model="vcardData.name"/>
                                        </div>
                                        <div class="p-vcard-info p-vcard-mobile">
                                            <label class="required" for="mobile">手机</label>
                                            <input autocomplete="off" data-id="14" disableautocomplete="" name="mobile" type="text" v-model="vcardData.mobile"/>
                                            <span class="add-mobile pointer" @click="addMobileField">添加手机</span>
                                        </div>
                                        <div v-for="(mobile, index) in extraMobiles" :key="'mobile-' + index" class="p-vcard-info">
                                            <label class="required" :for="'mobile' + (index + 2)">手机{{ index + 2 }}</label>
                                            <input autocomplete="off" :data-id="'mobile' + (index + 2)" disableautocomplete="" :name="'mobile' + (index + 2)" type="text" v-model="extraMobiles[index]"/>
                                            <span class="remove-item remove-item-mobile pointer" @click="removeMobileField(index)">删除</span>
                                        </div>
                                        <div class="p-vcard-info">
                                            <label for="email">邮箱</label>
                                            <input autocomplete="off" data-id="15" disableautocomplete="" name="email" type="text" v-model="vcardData.email"/>
                                        </div>

                                        <!-- Additional Contact Methods -->
                                        <div v-for="(contact, index) in additionalContacts" :key="'contact-' + index" class="p-vcard-info else-contact">
                                            <div class="dropdown">
                                                <span id="vcard-info-name" class="defaultDropDown">{{ contact.type }}</span>
                                            </div>
                                            <input :name="contact.type" :cname="contact.type" type="text" v-model="contact.value" autocomplete="off" disableautocomplete/>
                                            <span class="remove-item pointer" @click="removeAdditionalContact(index)">删除</span>
                                        </div>
                                    </div>

                                    <!-- Add Contact Method Button -->
                                    <div class="add-item" id="add-item">
                                        <i class="fa fa-plus-circle"></i>
                                        添加联系方式
                                        <div class="dropdown-menu text-xs">
                                            <div class="dropdown-item" data-contact="url" data-value="网址" @click="addContactMethod('网址', 'url')">网址</div>
                                            <div class="dropdown-item" data-contact="fax" data-value="传真" @click="addContactMethod('传真', 'fax')">传真</div>
                                            <div class="dropdown-item" data-contact="phone" data-value="电话" @click="addContactMethod('电话', 'phone')">电话</div>
                                            <div class="dropdown-item" data-contact="weixin" data-value="微信" @click="addContactMethod('微信', 'weixin')">微信</div>
                                            <div class="dropdown-item" data-contact="qq" data-value="QQ" @click="addContactMethod('QQ', 'qq')">QQ</div>
                                            <div class="dropdown-item" data-contact="weibo" data-value="微博" @click="addContactMethod('微博', 'weibo')">微博</div>
                                        </div>
                                    </div>

                                    <!-- Right Info Section -->
                                    <div class="right-info">
                                        <div class="p-vcard-info" style="position: relative;">
                                            <label class="" for="company">公司</label>
                                            <input autocomplete="off" data-id="16" disableautocomplete="" id="company" name="company" type="text" v-model="vcardData.company"/>
                                        </div>
                                        <div class="p-vcard-info">
                                            <label class="" for="dep">部门</label>
                                            <input autocomplete="off" data-id="17" disableautocomplete="" name="dep" type="text" v-model="vcardData.department"/>
                                        </div>
                                        <div class="p-vcard-info">
                                            <label class="" for="job">职位</label>
                                            <input autocomplete="off" data-id="18" disableautocomplete="" name="job" type="text" v-model="vcardData.position"/>
                                        </div>

                                        <!-- Additional Job Info -->
                                        <div v-for="(jobInfo, index) in additionalJobInfo" :key="'job-' + index" class="p-vcard-info">
                                            <label class="" :for="jobInfo.type">{{ jobInfo.type }}</label>
                                            <input autocomplete="off" :data-id="jobInfo.type" disableautocomplete="" :name="jobInfo.type" type="text" v-model="jobInfo.value"/>
                                            <span class="remove-item pointer" @click="removeJobInfo(index)">删除</span>
                                        </div>

                                        <!-- Add Job Info Button -->
                                        <div class="add-item" id="add-item1" style="margin-left: 0;">
                                            <i class="fa fa-plus-circle"></i>
                                            添加项目
                                            <div class="dropdown-menu text-xs">
                                                <a class="dropdown-item" data-contact="touxian" data-value="头衔" href="javascript:void(0);" @click="addJobInfo('头衔', 'touxian')">头衔</a>
                                            </div>
                                        </div>

                                        <div class="p-vcard-info" style="border-top: 1px dashed rgba(221,224,226,.8);">
                                            <label class="" for="address">地址</label>
                                            <input autocomplete="off" data-id="19" disableautocomplete="" name="address" type="text" v-model="vcardData.address"/>
                                        </div>
                                        <div class="p-vcard-info">
                                            <label class="" for="note">签名</label>
                                            <input autocomplete="off" data-id="22" disableautocomplete="" name="note" type="text" v-model="vcardData.signature"/>
                                        </div>
                                    </div>
                                </div>

                                <!-- Generate Button -->
                                <div class="person-form-btn-wrapper">
                                    <div class="person-btn">
                                        <button class="btn green btn-md btn-cli-green btn-green-shadow" :class="{'loading': isGenerating}" @click="generateVCard" :disabled="!canGenerate">
                                            {{ isGenerating ? '正在生成...' : '生成二维码' }}
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- QR Code Display Section -->
                            <div class="showVcardCode">
                                <div class="include-qrfun-origin">
                                    <div class="qrbox col-md-4 vcard-qrcode-wrapper" :class="{'noQrCode': !qrCodeUrl}" data-is_create_code="1" id="qrfun-box">
                                        <div class="qrcode-wrapper">
                                            <div class="qrfun-tab-content code-tab-content">
                                                <div class="qrcode">
                                                    <table class="qrimage-wrap b-a text-center" style="border-radius:4px;">
                                                        <tr>
                                                            <td class="qrimage-td-h" style="color:#ececec;font-size: 16px;">
                                                                <img v-if="qrCodeUrl" alt="生成的二维码" id="qrimage" :src="qrCodeUrl"/>
                                                                <div class="deqr-wrapper" id="deqr-wrapper">
                                                                    <a class="deqr-link" href="#" @click="decodeQr" style="padding-right: 0;padding-left: 4px;color: #666;" title="通过二维码图片，快速解析内容">
                                                                        <span class="clifont anticon-cli-scanning"></span>解码
                                                                    </a>
                                                                </div>
                                                                <span v-if="!qrCodeUrl" class="create-code-tip">
                                                                    <img alt="二维码未生成" src="../../assets/images/ee35eb02b46b.png"/>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    </table>

                                                    <!-- QR Code Bottom Tools -->
                                                    <ul class="sub_nav qrcode-bottom sub_mobile_nav clearfix pull-right" id="qrcode-bottom-tool">
                                                        <li class="popover_link pull-left nav-tool-popover-scan-new p-t-b-8 pointer mh-popover-origin" id="mh_link">
                                                            <div class="popover_link_wrap">
                                                                <a class="tab_sep m-r-0 divider code-meihua-style" href="#" @click="beautifyQrCode" style="display: inline-block;" title="快速美化二维码图案，上传logo等">
                                                                    <span class="clifont anticon-meihua"></span>美化
                                                                </a>
                                                            </div>
                                                        </li>
                                                        <li class="popover_link pull-left nav-tool-popover-scan-new p-t-b-8 pointer mh-popover-origin" id="style-label-created">
                                                            <div class="popover_link_wrap">
                                                                <a href="#" @click="createLabel" id="style-label-created-link">
                                                                    <span class="tab_sep m-r-0 code-meihua-style">
                                                                        <span class="clifont anticon-zhizuobiaoqian"></span>制作标签
                                                                    </span>
                                                                </a>
                                                            </div>
                                                        </li>
                                                    </ul>
                                                </div>

                                                <!-- QR Code Tools -->
                                                <div class="tools-v2 tools" v-if="qrCodeUrl" style="display: block;">
                                                    <div class="when-have-code">
                                                        <div class="tab-container">
                                                            <div class="qr-style-tab-item beautify" style="display: block; text-align: center; font-size: 0;margin-bottom: 8px;">
                                                                <div class="btn-block new-up-icon-btn-wrapper" style="width: 100%;display: inline-flex;">
                                                                    <button class="btn qrfun-btn qrfun-beautify-btn" @click="uploadLogo" style="margin-right: 6px;" type="button">上传Logo</button>
                                                                    <button class="btn qrfun-btn qrfun-beautify-btn" @click="beautifyQrCode" type="button">二维码美化</button>
                                                                    <button class="btn qrfun-btn qrfun-beautify-btn" @click="editFields" style="margin-left: 6px;" type="button">修改字段</button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Content tabs section -->
        <div class="tab-file-box new-light bottom-white-line">
            <div class="page-main-content" style="position: relative;">
                <div class="nav-fixed-empty"></div>
                <div id="tab-nav">
                    <ul class="tab-ul list_tab page-main-content">
                        <li class="tab-item noMarginLeft active" data-id="1" data-name="功能介绍" data-tab-id="1" data-tab-item="" data-tab-path="info" data-tab-type="blog" data-tab-url="/vcard" data-type="名片">
                            <a href="vcard.html" rel="canonical" title="功能介绍">功能介绍</a>
                        </li>
                        <li class="tab-item" data-id="3596" data-name="讨论" data-tab-id="3596" data-tab-item="" data-tab-path="comment" data-tab-type="comment" data-tab-url="/vcard/comment" data-type="名片">
                            <a href="vcard/comment.html" id="comment-tab-item" rel="canonical" title="讨论">讨论(212)</a>
                        </li>
                    </ul>
                </div>
                <a class="text-darkgrey back-to-old-version" href="http://biz.cli.im/vcard" id="vcard-to-old-version" onclick="StatisticsData(110,153)" rel="nofollow" target="_blank">返回旧版</a>
            </div>
        </div>

        <!-- Main content area -->
        <div class="w-p100 p-b-lg tab-vcard-box white tab-content-container">
            <div class="page-main-content white">
                <!-- Article content -->
                <div class="article-tab-box clearfix" id="article">
                    <div class="wordpress-article">
                        <div class="wiki wordpress-article-box doc-content inline" id="wordpress_article_box">
                            <div class="wordpress_article_info_box entry-content" id="wordpress_article_info_box">
                                <h2>主要功能</h2>
                                <p>草料名片二维码可替代纸质名片，方便转发分享，还能将二维码印刷在纸质名片上，作为纸质名片的拓展介绍，微信扫码即可查看和保存。</p>
                                <ul>
                                    <li><p>免费制作名片二维码，不限创建数量；</p></li>
                                    <li><p>扫码即可查看姓名、职位、拨打电话、地图导航、个人简介；</p></li>
                                    <li><p>支持一键保存到通讯录；</p></li>
                                    <li><p>在微信中可管理自己的名片，进行查看、编辑、转发等操作；</p></li>
                                    <li><p>实时统计名片被查看和被保存的数量，了解分发效果。</p></li>
                                </ul>

                                <h3>名片效果</h3>
                                <p><img alt="1616476009431097.png" data-height="813" data-width="1250" src="../../assets/images/115486105fca.png" title="名片效果展示"/></p>

                                <h3>常见问题</h3>
                                <h4>1. 为什么提示手机号错误，无法创建名片？</h4>
                                <ul>
                                    <li><p>手机号为必填项，不得为空</p></li>
                                    <li><p>核对输入的手机号位数是否正确；</p></li>
                                    <li><p>是否为大陆地区手机号，目前仅支持大陆手机号创建名片。</p></li>
                                </ul>

                                <h4>2. 如何创建英文名片？</h4>
                                <p>名片的字段会以图标的形式展示，只需要直接输入英文内容，即可生成英文名片，名片的按钮会跟随微信语音自动切换成英文。</p>
                                <p>因为名片是基于微信小程序开发的，所以仅支持微信扫码打开，如果名片主要应用于国外，需使用其他APP可以扫码打开名片，可前往使用 <a href="http://biz.cli.im/vcard">旧版名片</a></p>

                                <h4>3. 名片码上超过3个号码时，为什么不能全部保存到通讯录？</h4>
                                <p>受微信小程序接口的限制，保存到通讯录时最多只能保存3个号码（包含手机号和电话号码）。</p>
                                <p>因微信小程序与安卓手机的接口不适配的缘故，使用安卓手机保存名片时，需要自己手动选择一下名片字段。</p>

                                <h4>4. 如何修改名片的内容？</h4>
                                <p>自己的名片可以认领到微信中，在草料二维码小程序中进行修改。<a href="help/48431.html">了解详情</a></p>

                                <h4>5. 有扫码应用限制吗？</h4>
                                <p>名片码当前仅支持使用普通微信进行扫码查看。支付宝、企业微信、手机相机等其他应用均不支持。</p>
                            </div>
                        </div>
                        <div class="wikiOutlineWrapper" ref="outlineWrapper">
                            <ul class="wikiOutlineContainer" ref="outlineContainer">
                                <li v-for="(item, index) in outlineItems"
                                    :key="index"
                                    :class="['item', { active: activeOutlineIndex === index }]"
                                    :data-target-header="item.tagName"
                                    @click="scrollToHeader(item, index)">
                                    <span>{{ item.text }}</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modals and overlays -->
        <div class="help-modal-backdrop none" id="build-code-modal">
            <div class="help-modal-backdrop-bg"></div>
            <div class="help-modal">
                <button class="close help-modal-backdrop-close" type="button">
                    <span aria-hidden="true">×</span>
                    <span class="sr-only">关闭</span>
                </button>
                <div class="help-modal-title text-center">扫码认领名片</div>
                <div class="help-modal-content text-center">
                    <img alt="" src="../../assets/images/e29e220e1d71.png"/>
                    <p class="vcard-info">电脑端无法管理个人名片，请使用微信扫描上方<br/>小程序码，匹配手机号认领并管理该名片</p>
                    <p class="tip">如需电脑端管理，请使用 <span class="c-vcard-btn c-vcard-create pointer" @click="createEnterpriseVCard">企业名片二维码</span></p>
                </div>
            </div>
        </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'

// 定义组件名称
defineOptions({
  name: 'VcardPage'
})

// 定义页面元信息
const metaInfo = {
  title: '草料名片二维码生成器',
  meta: [
    { name: 'description', content: '草料二维码提供个人名片和企业名片免费制作、名片印刷等服务。3秒快速制作名片，草料名片具有分享、拨号、保存到通讯录、访客统计、批量添加、企业通讯录、企业主页、成员管理等功能，是你的商务拓展利器。' },
    { name: 'keywords', content: '名片,二维码,名片二维码,二维码名片,草料二维码,名片设计,个人名片,企业名片,名片模板,二维码生成器,企业名片二维码,电子名片,名片制作,小程序名片' },
    { property: 'og:title', content: '草料名片二维码生成器' },
    { property: 'og:description', content: '草料二维码提供个人名片和企业名片免费制作、名片印刷等服务。3秒快速制作名片，草料名片具有分享、拨号、保存到通讯录、访客统计、批量添加、企业通讯录、企业主页、成员管理等功能，是你的商务拓展利器。' },
    { property: 'og:image', content: 'https://gstatic.clewm.net/caoliao-resource/240407/6b2aef_89bd6906.png' },
    { name: 'referrer', content: 'no-referrer-when-downgrade' }
  ],
  link: [
    { rel: 'canonical', href: 'https://cli.im/vcard' },
    { rel: 'icon', type: 'image/x-icon', href: '../../assets/images/ceba46bf2ecc.ico' },
    { rel: 'shortcut icon', type: 'image/x-icon', href: '../../assets/images/ceba46bf2ecc.ico' }
  ]
}

// 名片数据
const vcardData = reactive({
  name: '',
  mobile: '',
  email: '',
  company: '',
  department: '',
  position: '',
  address: '',
  signature: '',
  avatar: ''
})

// 响应式数据
const extraMobiles = ref<string[]>([])
const additionalContacts = ref<Array<{type: string, value: string, fieldType: string}>>([])
const additionalJobInfo = ref<Array<{type: string, value: string, fieldType: string}>>([])

// UI状态
const isGenerating = ref<boolean>(false)
const showQrCode = ref<boolean>(false)
const qrCodeUrl = ref<string>('')
const defaultAvatar = ref<string>('../../assets/images/1ef5667e2599.png')
const wikiOutlineNavigatorIns = ref(null)

// Outline navigation state
const outlineItems = ref<Array<{ text: string, tagName: string, element: HTMLElement }>>([])
const activeOutlineIndex = ref(-1)
const isScrolling = ref(false)
const outlineWrapper = ref<HTMLElement>()
const outlineContainer = ref<HTMLElement>()

// 清理函数集合
const cleanupFunctions = ref<Array<() => void>>([])

// 计算属性
const canGenerate = computed(() => {
  return vcardData.name.trim() && vcardData.mobile.trim() && !isGenerating.value
})

const avatarUrl = computed(() => {
  // 如果有用户上传的头像，使用用户头像
  if (vcardData.avatar) {
    return vcardData.avatar
  }
  // 使用默认头像
  return defaultAvatar.value
})

// 统计数据函数
const StatisticsData = (fir: number, sec: number): void => {
  console.log('StatisticsData called:', fir, sec)
}

// ========== 文件上传相关 ==========
const triggerAvatarUpload = (): void => {
  const input = document.getElementById('uploadfile') as HTMLInputElement
  if (input) {
    input.click()
  }
}

const handleAvatarUpload = (event: Event): void => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file && file.type.startsWith('image/')) {
    // 创建文件预览
    const reader = new FileReader()
    reader.onload = (e) => {
      vcardData.avatar = e.target?.result as string
    }
    reader.readAsDataURL(file)
  } else {
    alert('请选择有效的图片文件')
  }
}

// ========== 表单字段管理 ==========
const addMobileField = (): void => {
  extraMobiles.value.push('')
}

const removeMobileField = (index: number): void => {
  extraMobiles.value.splice(index, 1)
}

const addContactMethod = (label: string, type: string): void => {
  additionalContacts.value.push({
    type: label,
    value: '',
    fieldType: type
  })
}

const removeAdditionalContact = (index: number): void => {
  additionalContacts.value.splice(index, 1)
}

const addJobInfo = (label: string, type: string): void => {
  additionalJobInfo.value.push({
    type: label,
    value: '',
    fieldType: type
  })
}

const removeJobInfo = (index: number): void => {
  additionalJobInfo.value.splice(index, 1)
}

// ========== 二维码生成 ==========
const generateVCard = async (): Promise<void> => {
  if (!canGenerate.value) {
    return
  }

  isGenerating.value = true

  try {
    // 验证手机号格式
    if (!validateMobile(vcardData.mobile)) {
      alert('请输入正确的手机号码')
      return
    }

    // 构建vCard数据
    const vcardContent = buildVCardContent()

    // 这里应该调用实际的API来生成二维码
    // 现在模拟生成过程
    await simulateQRGeneration(vcardContent)

    showQrCode.value = true

    // 显示认领提示
    setTimeout(() => {
      showClaimModal()
    }, 2000)

  } catch (error) {
    console.error('生成名片二维码失败:', error)
    alert('生成失败，请稍后重试')
  } finally {
    isGenerating.value = false
  }
}

const validateMobile = (mobile: string): boolean => {
  // 简单的手机号验证
  const mobileRegex = /^1[3-9]\d{9}$/
  return mobileRegex.test(mobile)
}

const buildVCardContent = (): string => {
  // 构建vCard格式内容
  let vcard = 'BEGIN:VCARD\nVERSION:3.0\n'

  vcard += `FN:${vcardData.name}\n`
  vcard += `TEL;TYPE=CELL:${vcardData.mobile}\n`

  // 添加额外手机号
  extraMobiles.value.forEach(mobile => {
    if (mobile.trim()) {
      vcard += `TEL;TYPE=CELL:${mobile}\n`
    }
  })

  if (vcardData.email) {
    vcard += `EMAIL:${vcardData.email}\n`
  }

  if (vcardData.company) {
    vcard += `ORG:${vcardData.company}`
    if (vcardData.department) {
      vcard += `;${vcardData.department}`
    }
    vcard += '\n'
  }

  if (vcardData.position) {
    vcard += `TITLE:${vcardData.position}\n`
  }

  if (vcardData.address) {
    vcard += `ADR:;;${vcardData.address};;;;\n`
  }

  if (vcardData.signature) {
    vcard += `NOTE:${vcardData.signature}\n`
  }

  // 添加额外联系方式
  additionalContacts.value.forEach(contact => {
    if (contact.value.trim()) {
      switch (contact.fieldType) {
        case 'url':
          vcard += `URL:${contact.value}\n`
          break
        case 'fax':
          vcard += `TEL;TYPE=FAX:${contact.value}\n`
          break
        case 'phone':
          vcard += `TEL;TYPE=WORK:${contact.value}\n`
          break
        default:
          vcard += `X-${contact.fieldType.toUpperCase()}:${contact.value}\n`
      }
    }
  })

  vcard += 'END:VCARD'
  return vcard
}

const simulateQRGeneration = async (content: string): Promise<void> => {
  // 模拟API调用延迟
  await new Promise(resolve => setTimeout(resolve, 2000))

  // 这里应该调用真实的二维码生成API
  // 现在使用模拟的二维码图片
  qrCodeUrl.value = ''

  console.log('生成的vCard内容:', content)
}

const showClaimModal = (): void => {
  const modal = document.getElementById('build-code-modal')
  if (modal) {
    modal.classList.remove('none')
    modal.classList.add('active')
    document.body.style.overflow = 'hidden'
  }
}

// ========== 二维码工具 ==========
const uploadLogo = (): void => {
  // TODO: 实现Logo上传功能
  console.log('上传Logo功能')
}

const beautifyQrCode = (): void => {
  // TODO: 实现二维码美化功能
  console.log('二维码美化功能')
}

const editFields = (): void => {
  // TODO: 实现字段编辑功能
  console.log('修改字段功能')
}

const createEnterpriseVCard = (): void => {
  // TODO: 创建企业名片
  console.log('创建企业名片')
}

const createLabel = (): void => {
  // TODO: 实现制作标签功能
  console.log('制作标签功能')
}

const decodeQr = (): void => {
  // TODO: 实现二维码解码功能
  console.log('解码二维码')
}

// ========== 图片加载处理 ==========
const handleImageError = (event: Event): void => {
  const target = event.target as HTMLImageElement
  console.error('图片加载失败:', target.src)
  console.log('尝试的路径:', avatarUrl.value)
  console.log('当前工作目录:', window.location.href)

  // 尝试备用路径
  const fallbackPaths = [
    '/src/views/qrcode/assets/images/1ef5667e2599.png'
  ]

  let currentIndex = parseInt(target.dataset.fallbackIndex || '0')
  if (currentIndex < fallbackPaths.length) {
    target.dataset.fallbackIndex = (currentIndex + 1).toString()
    target.src = fallbackPaths[currentIndex]
    console.log('尝试备用路径:', fallbackPaths[currentIndex])
  } else {
    console.error('所有备用路径都加载失败')
  }
}

const handleImageLoad = (event: Event): void => {
  const target = event.target as HTMLImageElement
  console.log('图片加载成功:', target.src)
}

// ========== 页面初始化相关 ==========
const initializePageVisibility = (): void => {
  // 确保主要内容区域可见
  const initContent = document.querySelector('.x-initContent') as HTMLElement
  if (initContent) {
    initContent.style.visibility = 'visible'
  }
}

const initializeFormFunctionality = (): void => {
  // 初始化表单功能
  console.log('初始化名片表单功能')
}

// 简化的jQuery等待函数
const waitForJQuery = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    const maxAttempts = 50
    let attempts = 0

    const checkJQuery = () => {
      attempts++
      if (typeof window.$ !== 'undefined' && typeof window.jQuery !== 'undefined') {
        console.log(`jQuery在第${attempts}次检查时可用`)
        resolve()
      } else if (attempts >= maxAttempts) {
        reject(new Error('等待jQuery超时'))
      } else {
        setTimeout(checkJQuery, 100)
      }
    }

    checkJQuery()
  })
}

// 简化的脚本加载
// Outline navigation functions
const initOutlineNavigation = () => {
  nextTick(() => {
    collectHeaders()
    setupScrollListener()
  })
}

const collectHeaders = () => {
  // Collect only h2, h3, and h4 elements from the wordpress article content
  const headers = document.querySelectorAll('.wordpress_article_info_box h2, .wordpress_article_info_box h3, .wordpress_article_info_box h4')
  outlineItems.value = Array.from(headers).map((header: HTMLElement) => ({
    text: header.textContent || '',
    tagName: header.tagName,
    element: header
  }))

  // Set the first item as active by default
  if (outlineItems.value.length > 0) {
    activeOutlineIndex.value = 0
  }

  // Show or hide outline container based on whether there are headers
  if (outlineWrapper.value) {
    if (outlineItems.value.length > 0) {
      outlineWrapper.value.style.display = 'block'
      outlineContainer.value?.classList.add('hasOutline')
    } else {
      outlineWrapper.value.style.display = 'none'
      outlineContainer.value?.classList.remove('hasOutline')
    }
  }
}

const setupScrollListener = () => {
  window.addEventListener('scroll', updateActiveOutline)
}

const updateActiveOutline = () => {
  if (isScrolling.value || outlineItems.value.length === 0) return

  let activeIndex = 0 // Default to first item
  const scrollTop = window.scrollY
  const headerOffsetTop = 100 // Offset for header detection

  // Find the current active header based on scroll position
  for (let i = 0; i < outlineItems.value.length; i++) {
    const element = outlineItems.value[i].element
    const elementTop = element.offsetTop - headerOffsetTop

    if (scrollTop >= elementTop) {
      activeIndex = i
    } else {
      break
    }
  }

  activeOutlineIndex.value = activeIndex
}

const isElementScrolled = (element: HTMLElement): boolean => {
  const rect = element.getBoundingClientRect()
  return rect.top <= 100 // Element is considered "scrolled past" when it's 100px from top
}

const scrollToHeader = (item: { element: HTMLElement, text: string }, index: number) => {
  if (activeOutlineIndex.value === index || isScrolling.value) return

  activeOutlineIndex.value = index
  isScrolling.value = true

  // Smooth scroll to the target header
  const offsetTop = item.element.offsetTop
  window.scrollTo({
    top: offsetTop,
    behavior: 'smooth'
  })

  // Reset scrolling flag after animation
  setTimeout(() => {
    isScrolling.value = false
  }, 800)
}

const loadExternalScripts = (): void => {
  console.log('VCard页面初始化 - 简化版本')
  // 简化实现，不依赖复杂的jQuery加载
}

// 生命周期
onMounted(() => {
  console.log('VCard组件mounted，开始初始化')

  // 初始化页面功能
  initializePageVisibility()
  initializeFormFunctionality()

  // 尝试加载外部脚本（简化版）
  loadExternalScripts()

  // Initialize outline navigation
  initOutlineNavigation()

  // 等待一段时间后尝试初始化导航（如果需要）
  setTimeout(() => {
    console.log('VCard页面初始化完成')
  }, 1000)
})

// 组件卸载时清理
onUnmounted(() => {
  cleanupFunctions.value.forEach(cleanup => cleanup())
  cleanupFunctions.value = []

  // Cleanup if needed
  wikiOutlineNavigatorIns.value = null

  // 清理jQuery相关事件监听（如果存在）
  if (typeof $ !== 'undefined') {
    $(window).off('scroll.outline')
  }
})
</script>

<style src="../../assets/css/490815b50ee0.css" scoped/>
<style src="../../assets/css/00b58f2b8f9a.css" scoped/>
<style src="../../assets/css/e88b6e80fbce.css" scoped/>
<style src="../../assets/css/f6d6073f1386.css" scoped/>
<style src="../../assets/css/b3291d7c3f11.css" scoped/>
<style src="../../assets/css/b76aaf663b7f.css" scoped/>
<style src="../../assets/css/5e6b9bf9fd2f.css" scoped/>
<style src="../../assets/css/4a89b0f71b15.css" scoped/>
<style src="../../assets/css/2034b15460f1.css" scoped/>
<style src="../../assets/css/dbece38160fc.css" scoped/>
<style src="../../assets/css/4f203d7b339f.css" scoped/>
<style src="../../assets/css/c1580d903c0f.css" scoped/>
<style src="../../assets/css/228034f02af3.css" scoped/>
<style src="../../assets/css/acfff1e57b0e.css" scoped/>
<style src="../../assets/css/3db6acd047a4.css" scoped/>
<style src="../../assets/css/550d0fc5c52a.css" scoped/>
<style src="../../assets/css/7272988962e3.css" scoped/>
<style src="../../assets/css/b64637f7e36e.css" scoped/>
<style src="../../assets/css/cac1baa43ce6.css" scoped/>

<style scoped>

/* 原始htmlpage中存在的样式 */
.mobile-scene-min-width {
  min-width: 1200px;
}


/* 修复生成二维码按钮颜色为深绿色 - 使用更强选择器 */
button.btn.green.btn-cli-green,
.btn.green.btn-cli-green {
  background-color: #00a13b !important;
  border-color: #00a13b !important;
  color: #fff !important;
  cursor: pointer !important;
  opacity: 1 !important;
}

button.btn.green.btn-cli-green:hover,
button.btn.green.btn-cli-green:focus,
.btn.green.btn-cli-green:hover,
.btn.green.btn-cli-green:focus {
  background-color: #008a32 !important;
  border-color: #008a32 !important;
  color: #fff !important;
  cursor: pointer !important;
  opacity: 1 !important;
}

/* 确保按钮有正确的pointer效果 - 覆盖所有可能的状态 */
.btn.green,
.btn.btn-cli-green,
button[type="button"],
.btn.green.btn-cli-green,
button.btn.green.btn-cli-green,
.person-btn button,
.person-btn .btn,
.person-form-btn-wrapper button,
.person-form-btn-wrapper .btn {
  cursor: pointer !important;
  pointer-events: auto !important;
}

/* 确保即使在hover状态下也有pointer */
.btn.green:hover,
.btn.btn-cli-green:hover,
button[type="button"]:hover,
.btn.green.btn-cli-green:hover,
button.btn.green.btn-cli-green:hover,
.person-btn button:hover,
.person-btn .btn:hover {
  cursor: pointer !important;
  pointer-events: auto !important;
}

/* 确保enabled状态有正确的pointer */
.btn.green:not([disabled]),
.btn.btn-cli-green:not([disabled]),
button[type="button"]:not([disabled]) {
  cursor: pointer !important;
  pointer-events: auto !important;
}

/* 甚至禁用状态也显示pointer（如果这是期望的行为）*/
.btn.green[disabled],
.btn.btn-cli-green[disabled],
button[type="button"][disabled] {
  cursor: pointer !important;
  pointer-events: auto !important;
  opacity: 0.8 !important;
}

/* 特别针对我们的按钮 */
.btn.green.btn-cli-green.btn-md.btn-green-shadow {
  cursor: pointer !important;
  pointer-events: auto !important;
}

.btn.green.btn-cli-green.btn-md.btn-green-shadow:hover {
  cursor: pointer !important;
  pointer-events: auto !important;
}

#wechat-area {
  position: relative;
  height: 100px;
}

#wechat-qr {
  width: 100px;
  height: 100px;
  vertical-align: bottom;
}

.logo-in-qrcode {
  position: absolute;
  left: 40px;
  top: 40px;
  width: 20px;
  height: 20px;
}

.logo-in-qrcode img {
    width: 100%;
    height: 100%;
}

.scan-success {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background-color: rgba(255,255,255,0.8);
    text-align: center;
    line-height: 100px;
    color: rgba(0, 0, 0, 0.87);
}

#email {
  width: 300px;
  border-radius: 4px;
}

.feedback-box .feedback-label {
  font-size: 14px;
  color: #777;
  width: 95px;
  line-height: 38px;
  float: left;
}

.feedback-box .feedback-content-500 {
  width: 408px;
}

.feedback-box .feedback-content {
  max-width: 100%;
  float: left;
}

.feedback-box .feedback-content .radio-inline {
  color: #666;
  margin-top: 10px;
}

#error-message {
  font-size: 12px;
}

.lity-content {
    /* transform: scale(1.2); */
    max-width: 96%;
}

.wikiOutlineWrapper {
  width: 260px !important;
  margin-left: 64px !important;
  margin-top: 0 !important;
  position: sticky !important;
  top: 80px !important;
  display: block !important;
  visibility: visible !important;
}
</style>
